<template>
  <div class="health-record-management">
    <!-- 查询筛选区域 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="老人ID">
          <el-input v-model="queryParams.elderlyUserId" placeholder="请输入老人ID" clearable />
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select v-model="queryParams.recordType" placeholder="请选择记录类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="血压" value="血压" />
            <el-option label="心率" value="心率" />
            <el-option label="血糖" value="血糖" />
            <el-option label="血脂" value="血脂" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否异常">
          <el-select v-model="queryParams.isAbnormal" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="正常" value="0" />
            <el-option label="异常" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="action-card" shadow="never">
      <el-button type="success" icon="Plus" @click="openAddDialog">新增记录</el-button>
      <el-button type="danger" icon="Delete" @click="batchDeleteRecords">批量删除</el-button>
      <span style="margin-left: 20px;">共 <b>{{ total }}</b> 条记录</span>
    </el-card>

    <!-- 健康记录表格 -->
    <el-card class="content-card" shadow="never">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="elderlyUserId" label="老人ID" align="center" />
        <el-table-column prop="recordType" label="数据类型" align="center" />
        <el-table-column label="测量值" align="center">
          <template #default="{ row }">
            <span v-if="row.recordType === '血压'">{{ row.value1 }}/{{ row.value2 }} {{ row.unit }}</span>
            <span v-else>{{ row.value1 }} {{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isAbnormal" label="是否异常" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isAbnormal === 1 ? 'danger' : 'success'">
              {{ row.isAbnormal === 1 ? '异常' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" align="center" show-overflow-tooltip width="200" />
        <el-table-column prop="recordedAt" label="测量时间" align="center" width="180" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="openEditDialog(row)">修改</el-button>
            <el-button text type="danger" size="small" @click="deleteRecord(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.current"
        :page-size="queryParams.size"
        :page-sizes="[5, 7, 9, 10]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        style="margin-top: 16px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleCancel">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="老人ID" prop="elderlyUserId">
          <el-input v-model.number="formData.elderlyUserId" placeholder="请输入老人ID" />
        </el-form-item>
        <el-form-item label="数据类型" prop="recordType">
          <el-select
            v-model="formData.recordType"
            placeholder="请选择或输入类型"
            filterable
            allow-create
            @change="handleRecordTypeChange"
            style="width: 100%"
          >
            <el-option label="血压" value="血压" />
            <el-option label="心率" value="心率" />
            <el-option label="血糖" value="血糖" />
            <el-option label="血脂" value="血脂" />
          </el-select>
        </el-form-item>

        <el-form-item :label="formData.recordType === '血压' ? '收缩压' : '测量值'" prop="value1">
          <el-input v-model="formData.value1" placeholder="请输入测量值" />
        </el-form-item>
        <el-form-item v-if="formData.recordType === '血压'" label="舒张压" prop="value2">
          <el-input v-model="formData.value2" placeholder="请输入测量值" />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="是否异常" prop="isAbnormal">
          <el-radio-group v-model="formData.isAbnormal">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="formData.notes" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import healthRecordApi from '@/api/healthRecord'

// 查询参数
const queryParams = reactive({
  elderlyUserId: '',
  recordType: '',
  isAbnormal: '',
  startTime: '',
  endTime: '',
  current: 1,
  size: 5
})
const dateRange = ref([])

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 表格多选
const multipleTableRef = ref(null)
const multipleSelection = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

const defaultFormData = {
  id: null,
  elderlyUserId: '',
  recordType: '',
  value1: '',
  value2: '',
  unit: '',
  isAbnormal: 0,
  notes: '',
  createdByAdminId: 1 // 假设管理员ID为1
}
const formData = reactive({ ...defaultFormData })

const unitMap = {
  血压: 'mmHg',
  心率: 'bpm',
  血糖: 'mmol/L',
  血脂: 'mmol/L'
}

// 表单规则
const formRules = reactive({
  elderlyUserId: [{ required: true, message: '请输入老人ID', trigger: 'blur' }],
  recordType: [{ required: true, message: '请选择或输入数据类型', trigger: 'change' }],
  value1: [{ required: true, message: '请输入测量值', trigger: 'blur' }],
  value2: [
    {
      validator: (rule, value, callback) => {
        if (formData.recordType === '血压' && !value) {
          callback(new Error('请输入舒张压'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  isAbnormal: [{ required: true, message: '请选择是否异常', trigger: 'change' }]
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { elderlyUserId, recordType, isAbnormal, startTime, endTime, current, size } = queryParams
    const response = await healthRecordApi.page(
      elderlyUserId,
      current,
      size,
      recordType,
      isAbnormal,
      startTime,
      endTime
    )
    tableData.value = response.records
    total.value = Number(response.total)
  } catch (e) {
    ElMessage.error('获取健康记录失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.current = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    elderlyUserId: '',
    recordType: '',
    isAbnormal: '',
    startTime: '',
    endTime: '',
    current: 1,
    size: 5
  })
  dateRange.value = []
  fetchData()
}

// 日期范围变化
const handleDateChange = (val) => {
  queryParams.startTime = val ? val[0] : ''
  queryParams.endTime = val ? val[1] : ''
}

// 处理多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 切换每页条数
const handleSizeChange = (newSize) => {
  queryParams.size = newSize
  fetchData()
}

// 打开新增弹窗
const openAddDialog = () => {
  Object.assign(formData, defaultFormData)
  dialogTitle.value = '新增健康记录'
  dialogVisible.value = true
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 打开编辑弹窗
const openEditDialog = (row) => {
  Object.assign(formData, row)
  dialogTitle.value = '编辑健康记录'
  dialogVisible.value = true
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 弹窗关闭/取消
const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 记录类型变化时，自动填充单位
const handleRecordTypeChange = (value) => {
  formData.unit = unitMap[value] || ''
  // 如果从血压切换到其他类型，清空舒张压的值和校验
  if (value !== '血压') {
    formData.value2 = ''
  }
  formRef.value?.clearValidate(['value2'])
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formData.id) {
          await healthRecordApi.update(formData)
          ElMessage.success('更新成功')
        } else {
          await healthRecordApi.add(formData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (e) {
        ElMessage.error(e.message || (formData.id ? '更新失败' : '新增失败'))
      }
    }
  })
}

// 删除记录
const deleteRecord = (id) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await healthRecordApi.deleteById(id)
        ElMessage.success('删除成功')
        fetchData()
      } catch (e) {
        ElMessage.error(e.message || '删除失败')
      }
    })
    .catch(() => { }) // 用户点击取消
}

// 批量删除
const batchDeleteRecords = () => {
  const selectedIds = multipleSelection.value.map((item) => item.id)
  if (selectedIds.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await healthRecordApi.batchDelete(selectedIds)
        ElMessage.success('批量删除成功')
        fetchData()
      } catch (e) {
        ElMessage.error(e.message || '批量删除失败')
      }
    })
    .catch(() => { }) // 用户点击取消
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.health-record-management {
  width: 98%;
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.query-card,
.action-card,
.content-card {
  margin-bottom: 16px;
}

/* 优化内联表单项间距 */
.el-form--inline .el-form-item {
  margin-right: 12px;
  margin-bottom: 12px;
  /* 在换行时提供垂直间距 */
}
</style>